package com.ruoyi.util.security;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.config.SecurityConfig;
import com.ruoyi.info.domain.CmsApp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;

public class AppScanUtil {
    public static final Logger logger = LoggerFactory.getLogger(AppScanUtil.class);

    private static final String Android = "/Securityscan/";
    private static final String iOS = "/Securityscanios/";

    /**
     * 上传app
     * @param basePath 回调基础路径
     * @param batchId   批次号
     * @param file 文件
     * @param lx 上传类型 apk/ipa
     * @return
     */
    public static Result uploadApp(String basePath, String batchId, File file, String lx) {
        String path = getBasePath(lx) + "upload";
        String token = SecurityConfig.getInstance().getToken();

        String callbackBaseUrl = SecurityConfig.getInstance().getCallbackBaseUrl();
        if(StringUtils.isEmpty(callbackBaseUrl)) {
            callbackBaseUrl = basePath;
        }

        callbackBaseUrl += "/app/uploadCallback";

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("file", file);
        paramMap.put("batchId", batchId);
        paramMap.put("scanType", "0"); // 扫描类型，默认值是0,0:特定扫描,1:全扫描,2:sdk扫描
        paramMap.put("fileType", "0"); // 文件类型，默认值是0,0:apk,1:sdk{aar},2:sdk{zip},3:hap
        paramMap.put("uploadType", lx); // 文件类型，url(链接上传)/apk（文件上传）
        paramMap.put("callbackUrl", callbackBaseUrl); // 回调url，通知扫描结果

        System.out.println(">>>>" + paramMap);

        String result = HttpRequest.post(path)
                        .header("auth-key", token)
                        .form(paramMap)
                        .execute().body();
        System.out.println("----result:" + result);
        Result rs = JSON.parseObject(result, Result.class);
        return rs;
    }

    public static String getBasePath(String lx) {
        String host = SecurityConfig.getInstance().getHost();
        String ctx = "apk".equals(lx) ? Android : iOS;

        return host + ctx;
    }

    /**
     * 刷新数据
     * @param app
     */
    public static Result refreshRemote(CmsApp app) {
        String lx = app.getExt1();
        String md5 = app.getMd5();
        String batchId = app.getBatchId();

        String path = getBasePath(lx) + "query";
        String token = SecurityConfig.getInstance().getToken();

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("batchId", batchId);
        paramMap.put("md5", md5);


        logger.info("query请求参数：{}", paramMap);
        String result = HttpRequest.get(path)
                .header("auth-key", token)
                .form(paramMap)
                .execute().body();
        logger.info("query返回结果：{}", result);

        Result rs = JSON.parseObject(result, Result.class);
        return rs;
    }

    public static File getPdfUrl(CmsApp app) throws Exception {
        String lx = app.getExt1();
        String md5 = app.getMd5();
        String batchId = app.getBatchId();

        String token = SecurityConfig.getInstance().getToken();
        String path = getBasePath(lx) + "pdf?md5=" + md5 + "&batchId=" + batchId ;

        logger.info("---下载链接地址：{}", path);

        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为5秒
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestProperty("auth-key", token);
        InputStream inputStream = conn.getInputStream();

        byte[] getData = readInputStream(inputStream);

        String savePath = RuoYiConfig.getProfile() + File.separator + "download";

        File saveDir = new File(savePath);
        if (!saveDir.exists()) { // 没有就创建该文件
            saveDir.mkdir();
        }

        //获取文件名及后缀
        String fileName = URLDecoder.decode(batchId + ".pdf", "utf-8");
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        fos.close();
        inputStream.close();

        return file;
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[4 * 1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static Result getRemoteDetails(CmsApp app) {
        String lx = app.getExt1();
        String relateId = app.getRelativeId();
        String batchId = app.getBatchId();

        String path = getBasePath(lx) + "detail";
        String token = SecurityConfig.getInstance().getToken();

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("batchId", batchId);
        paramMap.put("id", relateId);


        logger.info("detail请求参数：{}", paramMap);
        String result = HttpRequest.get(path)
                .header("auth-key", token)
                .form(paramMap)
                .execute().body();
        logger.info("detail返回结果：{}", result);
        Result rs = JSON.parseObject(result, Result.class);
        return rs;
    }
}
